//
//  PickIconViewController.m
//  FootPrint
//
//  Created by alex tao on 4/24/13.
//  Copyright (c) 2013 alex tao. All rights reserved.
//

#import <MobileCoreServices/MobileCoreServices.h>
#import "PickIconViewController.h"
#import "JWFolders.h"
#import "UIImage+GImageExtension.h"

@interface PickIconViewController (){

    BOOL _userIconMode;//用户头相不能用系统图片
}

@end

@implementation PickIconViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        _subGridScroll = [[GridScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 200)];
        _subGridScroll.gridDelegate = self;
        _subGridScroll.backgroundColor = [UIColor darkGrayColor];
        
        _customImgArr = [[NSMutableArray alloc] initWithCapacity:8];
        _customPickIdx = -1;
        
        _parser = [[ImageParser alloc] init];
        _parser.delegate = self;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    if (_disableSysImg) {
        _pickSegment.selectedSegmentIndex = 1;
        _pickSegment.hidden = YES;
    } else {
        _pickSegment.selectedSegmentIndex = 0;
    }

    if(_userIconMode){
        [self.pickSegment setHidden:YES];
    }
    _gridScroll.gridDelegate = self;
    [self reloadGridScroll];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    _parser.delegate = nil;
    [_parser release];
    [_customImgArr release];
    [_subGridScroll release];
    [_gridScroll release];
    [_pickSegment release];
    [super dealloc];
}

- (void)viewDidUnload {
    [self setGridScroll:nil];
    [self setPickSegment:nil];
    [super viewDidUnload];
}

- (void)setUserMode{
    
    [self.pickSegment setHidden:YES];
    _userIconMode = YES;
    [self reloadGridScroll];
}

- (void) reloadGridScroll
{
    NSMutableArray * cateViews = [[[NSMutableArray alloc] initWithCapacity:11] autorelease];
    
    if (_pickSegment.selectedSegmentIndex == 0 && !_userIconMode) {
        for (int i = 0; i < 11; i++) {
            NSString * cateName = [NSString stringWithFormat:@"cate_%d.png", i+1];
            UIImageView * cateImg = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:cateName]] autorelease];
            cateImg.frame = CGRectMake(0, 0, 60, 60);
            [cateViews addObject:cateImg];
        }
    } else {
        [_customImgArr removeAllObjects];
        NSArray * tmpArr = [[ImageManager sharedInstance] allImages];
        for (NSString * eachId  in tmpArr) {
            NSString * imgUrl = [[ImageManager sharedInstance] imageFileForImageId:[eachId longLongValue]];
            UIImage * customImg = [UIImage imageWithContentsOfFile:imgUrl];
            
            if (customImg) {
                UIImageView * cell = [[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)] autorelease];
                cell.image = customImg;
                [cateViews addObject:cell];
                
                [_customImgArr addObject:eachId];
            } else {
                [[ImageManager sharedInstance] removeImageById:[eachId longLongValue]];
            }
        }
        
        
        UIImageView * cell = [[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)] autorelease];
        cell.image = [UIImage imageNamed:@"add.png"];
        [cateViews addObject:cell];
    }
    
    _gridScroll.cells = cateViews;
}

- (void) setupSubGridScrollOfIndex:(NSInteger)idx
{
    NSMutableArray * cateViews = [[[NSMutableArray alloc] initWithCapacity:8] autorelease];
    for (int i = 1; i < 100; i++)
    {
        NSString * sysName = [NSString stringWithFormat:@"sys_%02d%02d", idx, i];
        UIImage * sysImg = [UIImage imageNamed:sysName];
        if (sysImg) {
            UIImageView * cateImg = [[[UIImageView alloc] initWithImage:sysImg] autorelease];
            cateImg.frame = CGRectMake(0, 0, 60, 60);
            [cateViews addObject:cateImg];
        } else {
            break;
        }
    }
    
    _subGridScroll.cells = cateViews;
    [_subGridScroll layoutSubviews];
    
    CGSize fullSz = _subGridScroll.contentSize;
    if (fullSz.height > 240) {
        fullSz.height = 240;
    }
    if (fullSz.height < 80) {
        fullSz.height = 80;
    }
    _subGridScroll.bounds = CGRectMake(0, 0, fullSz.width, fullSz.height);
}

- (IBAction)segmentChange:(id)sender
{
    [self reloadGridScroll];
}

- (IBAction)exit:(id)sender {
    if (self.navigationController.viewControllers.count > 1) {
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        [self.navigationController dismissModalViewControllerAnimated:YES];
    }
}


#pragma mark - GridScrollDelegate

- (void) didSelect:(GridScrollView *)gridScroll atTotalIndex:(NSInteger)idx
{
    if (_pickSegment.selectedSegmentIndex == 0) {
        if (gridScroll == _gridScroll) {
            _openIdx = idx;
            [self setupSubGridScrollOfIndex:idx];
            [JWFolders openFolderWithContentView:_subGridScroll position:CGPointMake(160, ceilf((idx+1)/4.0) * 80 + 50) containerView:self.view sender:self];
        } else if (gridScroll == _subGridScroll) {
            NSString * imgName = [NSString stringWithFormat:@"sys_%02d%02d", _openIdx, idx+1];
            if (_pickDelegate && [_pickDelegate respondsToSelector:@selector(didPickSysImage:)]) {
                [_pickDelegate didPickSysImage:imgName];
            }
            if (_pickMode) {
                [JWFolders closeCurrentFolder];
                _openIdx = 0;
                [self exit:nil];
            }
        }
    } else if (_pickSegment.selectedSegmentIndex == 1 && gridScroll == _gridScroll) {
        if (idx < _customImgArr.count) {
            _customPickIdx = idx;
            UIActionSheet * actionSheet = nil;
            if (_pickMode) {
                actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                          delegate:self
                                                 cancelButtonTitle:@"取消"
                                            destructiveButtonTitle:nil
                                                 otherButtonTitles:@"选择", @"删除", nil];
            } else {
                actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                          delegate:self
                                                 cancelButtonTitle:@"取消"
                                            destructiveButtonTitle:nil
                                                 otherButtonTitles:@"删除", nil];
            }
            actionSheet.tag = 2000;
            [actionSheet showInView:self.view];
            [actionSheet release];
        } else if (idx == _customImgArr.count) {
            UIActionSheet * actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                                      delegate:self
                                                             cancelButtonTitle:@"取消"
                                                        destructiveButtonTitle:nil
                                                             otherButtonTitles:@"用相机拍摄", @"从相册选取", nil];
            actionSheet.tag = 1000;
            [actionSheet showInView:self.view];
            [actionSheet release];
        }
    }
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString * title = [actionSheet buttonTitleAtIndex:buttonIndex];
    if ([title isEqualToString:@"取消"]) {
        return;
    }
    
    if (actionSheet.tag == 1000)
    {
        UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.allowsEditing = YES;
        
        if ([title isEqualToString:@"用相机拍摄"])
        {
            imagePicker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        }
        else if ([title isEqualToString:@"从相册选取"])
        {
            imagePicker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
            imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        }
        
        [self.navigationController presentModalViewController:imagePicker animated:YES];
    }
    else if (actionSheet.tag == 2000 && _customPickIdx >= 0 && _customPickIdx < _customImgArr.count)
    {
        long long imgId = [[_customImgArr objectAtIndex:_customPickIdx] longLongValue];
        
        if ([title isEqualToString:@"选择"])
        {
            if (_pickDelegate && [_pickDelegate respondsToSelector:@selector(didPickCustomImage:)]) {
                [_pickDelegate didPickCustomImage:imgId];
            }
            [self exit:nil];
        }
        else if ([title isEqualToString:@"删除"])
        {
            [[ImageManager sharedInstance] removeImageById:imgId];
            [self reloadGridScroll];
        }
        _customPickIdx = -1;
    }
}


#pragma mark - UIImagePickerControllerDelegate

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissModalViewControllerAnimated:YES];
    if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:(NSString*)kUTTypeImage]) {
        UIImage* image = [info objectForKey:UIImagePickerControllerEditedImage];
        
        UIImage * fixImg = [image imageByScalingToSize:CGSizeMake(200, 200)];

        [_parser uploadImage:fixImg];
        [[GAlertLoadingView sharedAlertLoadingView] show];
        
    } else if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:(NSString*)kUTTypeMovie]) {
        [[iToast makeText:@"请选择图片资源!"] show];
    }
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissModalViewControllerAnimated:YES];
}


#pragma mark - ImageUploadDelegate

- (void)didUploadImage:(CustomedImageResponseMessage*)userMsg
{
    [[GAlertLoadingView sharedAlertLoadingView] hide];
    
    [self reloadGridScroll];
}

@end
